<?php

namespace liketp\database\concern;

use liketp\Model;
use liketp\model\Collection;

trait ResultOperate
{
    protected function processResult(array $result, bool $isCollection = false)
    {
        if ($this->model) {
            return $isCollection ? $this->resultToCollection($result) : $this->resultToModel($result, false);
        } else {
            return $result;
        }
    }

    protected function resultToModel(?array $data, bool $forceTransform = false): ?Model
    {
        if (is_array($data) || $forceTransform) {
            $modelClass = is_string($this->model) ? $this->model : get_class($this->model);
            $model = new $modelClass($data);
            $model->isExists(true);
            return $model;
        } else {
            return null;
        }
    }

    protected function resultToCollection(array $list): Collection
    {
        $collection = new Collection(get_class($this->model));

        foreach ($list as $data) {
            $item = $this->resultToModel($data);
            $collection->push($item);
        }
        return $collection;
    }
}
